<template>
  <div class="sanitation-fee-management">

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleGenerate" v-if="canCreate">
            <el-icon><Plus /></el-icon>
            生成卫生费
          </el-button>
        </el-col>

      </el-row>
    </el-card>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryForm" inline>
        <el-form-item label="社区">
          <el-select v-model="queryForm.communityId" placeholder="请选择社区" clearable @change="handleCommunityChange" style="width: 200px;">
            <el-option 
              v-for="community in communityList" 
              :key="community.id" 
              :label="community.communityName" 
              :value="community.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋">
          <el-select v-model="queryForm.buildingId" placeholder="请选择楼栋" clearable @change="handleBuildingChange" style="width: 200px;">
            <el-option 
              v-for="building in buildingList" 
              :key="building.id" 
              :label="building.buildingName" 
              :value="building.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单元">
          <el-select v-model="queryForm.unitId" placeholder="请选择单元" clearable @change="handleUnitChange" style="width: 200px;">
            <el-option 
              v-for="unit in unitList" 
              :key="unit.id" 
              :label="unit.unitName" 
              :value="unit.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房户">
          <el-select v-model="queryForm.roomId" placeholder="请选择房户" clearable style="width: 200px;">
            <el-option 
              v-for="room in roomList" 
              :key="room.id" 
              :label="room.roomNumber" 
              :value="room.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费状态">
          <el-select v-model="queryForm.paymentStatus" placeholder="请选择缴费状态" clearable style="width: 150px;">
            <el-option label="未缴费" :value="0" />
            <el-option label="已缴费" :value="1" />
            <el-option label="逾期" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 卫生费列表 -->
    <el-card class="table-card">
      <el-table v-loading="tableLoading" :data="sanitationFeeList" stripe>
        <el-table-column prop="feeNo" label="收费单号" width="120" />
        <el-table-column prop="householdAddress" label="房户地址" min-width="250" />
        <el-table-column prop="billingPeriod" label="计费月份" width="120" />
        <el-table-column prop="amount" label="费用金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="到期日期" width="120">
          <template #default="{ row }">
            <span :class="getDueDateClass(row.dueDate, row.paymentStatus)">
              {{ formatDate(row.dueDate) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="缴费状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
              {{ getPaymentStatusText(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button 
                v-if="canUpdate && row.paymentStatus !== 1"
                type="primary" 
                size="small" 
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0 && canUpdate"
                type="success" 
                size="small" 
                @click="handlePay(row)"
              >
                缴费
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0 && canUpdate"
                type="warning" 
                size="small" 
                @click="handleRemind(row)"
              >
                催缴
              </el-button>
              <el-button size="small" @click="handleViewDetail(row)">
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 生成卫生费弹窗 -->
    <el-dialog v-model="generateVisible" title="生成卫生费" width="500px">
      <el-form :model="generateForm" label-width="100px">
        <el-form-item label="社区">
          <el-select v-model="generateForm.communityId" placeholder="请选择社区" style="width: 100%">
            <el-option 
              v-for="community in communityList" 
              :key="community.id" 
              :label="community.communityName" 
              :value="community.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计费月份" prop="billingMonthRange">
          <el-date-picker
            v-model="generateForm.billingMonthRange"
            type="monthrange"
            placeholder="选择计费月份时间段"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 100%"
            range-separator="~"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          />
        </el-form-item>
        <el-form-item label="到期日期" prop="dueDate">
          <el-date-picker
            v-model="generateForm.dueDate"
            type="date"
            placeholder="选择到期日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGenerate" :loading="generating">
          确认生成
        </el-button>
      </template>
    </el-dialog>



    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="卫生费详情" width="1000px">
      <el-tabs v-model="detailTab" @tab-click="handleDetailTabClick">
        <el-tab-pane label="基本信息" name="base">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="账单ID">{{ currentFee?.id }}</el-descriptions-item>
            <el-descriptions-item label="收费单号">{{ currentFee?.feeNo }}</el-descriptions-item>
            <el-descriptions-item label="用户ID">{{ currentFee?.userId }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ currentFee?.userName }}</el-descriptions-item>
            <el-descriptions-item label="社区ID">{{ currentFee?.communityId }}</el-descriptions-item>
            <el-descriptions-item label="社区名称">{{ currentFee?.communityName }}</el-descriptions-item>
            <el-descriptions-item label="楼栋ID">{{ currentFee?.buildingId }}</el-descriptions-item>
            <el-descriptions-item label="楼栋名称">{{ currentFee?.buildingName }}</el-descriptions-item>
            <el-descriptions-item label="单元ID">{{ currentFee?.unitId }}</el-descriptions-item>
            <el-descriptions-item label="单元名称">{{ currentFee?.unitName }}</el-descriptions-item>
            <el-descriptions-item label="房户ID">{{ currentFee?.householdId }}</el-descriptions-item>
            <el-descriptions-item label="房户号">{{ currentFee?.householdCode }}</el-descriptions-item>
            <el-descriptions-item label="房户地址">{{ currentFee?.householdAddress }}</el-descriptions-item>
            <el-descriptions-item label="计费月份">{{ currentFee?.billingPeriod }}</el-descriptions-item>
            <el-descriptions-item label="费用金额">¥{{ currentFee?.amount }}</el-descriptions-item>
            <el-descriptions-item label="到期日期">{{ formatDate(currentFee?.dueDate) }}</el-descriptions-item>
            <el-descriptions-item label="缴费状态">
              <el-tag :type="getPaymentStatusTagType(currentFee?.paymentStatus)">
                {{ getPaymentStatusText(currentFee?.paymentStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="已支付金额">¥{{ currentFee?.paymentAmount || 0 }}</el-descriptions-item>
            <el-descriptions-item label="支付时间">{{ formatDateTime(currentFee?.paymentTime) }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ currentFee?.remark || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(currentFee?.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatDateTime(currentFee?.updateTime) }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="催缴/沟通" name="reminder" v-if="currentFee">
          <ReminderRecordPanel
            :feeId="Number(currentFee.id)"
            :feeType="1"
            :canEdit="canUpdate"
            ref="reminderPanelRef"
            @sync-success="handleSyncSuccess"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editVisible" title="编辑卫生费" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="账单ID" prop="id">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <el-form-item label="收费单号" prop="feeNo">
          <el-input v-model="editForm.feeNo" disabled />
        </el-form-item>
        <el-form-item label="房户地址" prop="householdAddress">
          <el-input v-model="editForm.householdAddress" disabled />
        </el-form-item>
        <el-form-item label="计费月份" prop="billingPeriod">
          <el-input v-model="editForm.billingPeriod" disabled />
        </el-form-item>
        <el-form-item label="费用金额" prop="amount">
          <el-input-number 
            v-model="editForm.amount" 
            :precision="2" 
            :min="0.01"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="到期日期" prop="dueDate">
          <el-date-picker
            v-model="editForm.dueDate"
            type="date"
            placeholder="选择到期日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            disabled
          />
        </el-form-item>
        <el-form-item label="缴费状态" prop="paymentStatus">
          <el-select v-model="editForm.paymentStatus" placeholder="请选择缴费状态" style="width: 100%">
            <el-option label="未缴费" :value="0" />
            <el-option label="已缴费" :value="1" />
            <el-option label="逾期" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit" :loading="editing">
          确认编辑
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Plus, DocumentAdd, Bell, Download } from '@element-plus/icons-vue'
import { sanitationFeeApi } from '@/api/property'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { householdApi } from '@/api/household'
import ReminderRecordPanel from './components/ReminderRecordPanel.vue'
import { ref as vueRef, nextTick } from 'vue'

import { useUserStore } from '@/store/user'
import { PermissionComputedManager } from '@/utils/permission'
import type { SanitationFee, BaseQueryParams } from '@/views/property/types/property'
import { showMessage } from '@/utils/message'

// 响应式数据
const tableLoading = ref(false)
const generating = ref(false)
const editing = ref(false)
const paying = ref(false)
const generateVisible = ref(false)
const detailVisible = ref(false)
const editVisible = ref(false)
const paymentVisible = ref(false) // 新增
const currentFee = ref<SanitationFee | null>(null)
const editFormRef = ref()
const paymentFormRef = ref() // 新增
const detailTab = vueRef<string>('base')
const reminderPanelRef = vueRef()

function handleDetailTabClick(tab: { paneName: string }) {
  if (tab.paneName === 'reminder' && reminderPanelRef.value) {
    nextTick(() => {
      reminderPanelRef.value.fetchReminders && reminderPanelRef.value.fetchReminders();
    });
  }
}

// 编辑表单
const editForm = reactive({
  id: 0,
  feeNo: '',
  householdAddress: '',
  billingPeriod: '',
  amount: 0,
  dueDate: '',
  paymentStatus: 0
})

// 编辑表单验证规则
const editRules = {
  amount: [
    { required: true, message: '请输入费用金额', trigger: 'blur' },
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请输入费用金额'))
        } else if (typeof value === 'number' && value <= 0) {
          callback(new Error('费用金额必须大于0'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  dueDate: [
    { required: true, message: '请选择到期日期', trigger: 'change' }
  ],
  paymentStatus: [
    { required: true, message: '请选择缴费状态', trigger: 'change' }
  ]
}

// 权限判断
const isSuperAdmin = computed(() => PermissionComputedManager.isSuperAdmin)
const hasPropertyCompany = computed(() => PermissionComputedManager.hasPropertyCompany)
const canCreate = computed(() => isSuperAdmin.value || hasPropertyCompany.value)
const canUpdate = computed(() => isSuperAdmin.value || hasPropertyCompany.value)
const canExport = computed(() => isSuperAdmin.value || hasPropertyCompany.value)

// 下拉列表数据
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])
const unitList = ref<any[]>([])
const roomList = ref<any[]>([])
const sanitationFeeList = ref<SanitationFee[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const queryForm = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  roomId: undefined as number | undefined,
  paymentStatus: undefined as number | undefined,
  billingMonth: ''
})

const generateForm = reactive({
  communityId: undefined as number | undefined,
  billingMonthRange: [] as string[], // 新增
  dueDate: '' // 新增
})



// 加载社区列表
const loadCommunityList = async () => {
  try {
    const response = await communityApi.getCommunityList({})
    if (response.code === 200) {
      // 确保数据是数组格式，处理分页和非分页两种情况
      let data = response.data
      if (data && typeof data === 'object' && data.records) {
        // 分页数据格式
        data = data.records
      } else if (!Array.isArray(data)) {
        // 如果不是数组，设为空数组
        data = []
      }
      // 过滤掉没有有效id的数据
      communityList.value = data.filter((item: any) => item && item.id != null)
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    showMessage({ type: 'error', message: '加载社区列表失败' })
  }
}

// 级联选择事件处理
const handleCommunityChange = async (communityId: number) => {
  queryForm.buildingId = undefined
  queryForm.unitId = undefined
  queryForm.roomId = undefined
  buildingList.value = []
  unitList.value = []
  roomList.value = []
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      buildingList.value = (response.data || []).filter((item: any) => item && item.id != null)
    } catch (error) {
      console.error('加载楼栋列表失败:', error)
      showMessage({ type: 'error', message: '加载楼栋列表失败' })
      buildingList.value = []
    }
  }
}

const handleBuildingChange = async (buildingId: number) => {
  queryForm.unitId = undefined
  queryForm.roomId = undefined
  unitList.value = []
  roomList.value = []
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      unitList.value = (response.data || []).filter((item: any) => item && item.id != null)
    } catch (error) {
      console.error('加载单元列表失败:', error)
      showMessage({ type: 'error', message: '加载单元列表失败' })
      unitList.value = []
    }
  }
}

const handleUnitChange = async (unitId: number) => {
  queryForm.roomId = undefined
  roomList.value = []
  
  if (unitId) {
    try {
      const response = await unitApi.getUnitHouseholds(unitId)
      roomList.value = (response.data || []).filter((item: any) => item && item.id != null)
    } catch (error) {
      console.error('加载房户列表失败:', error)
      showMessage({ type: 'error', message: '加载房户列表失败' })
      roomList.value = []
    }
  }
}



// 获取卫生费列表
const getSanitationFeeList = async () => {
  try {
    tableLoading.value = true
    const params: any = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 只添加非undefined的参数
    if (queryForm.communityId !== undefined) params.communityId = queryForm.communityId
    if (queryForm.paymentStatus !== undefined) params.paymentStatus = queryForm.paymentStatus
    if (queryForm.billingMonth) params.billingPeriod = queryForm.billingMonth
    if (queryForm.buildingId !== undefined) params.buildingId = queryForm.buildingId
    if (queryForm.unitId !== undefined) params.unitId = queryForm.unitId
    if (queryForm.roomId !== undefined) params.householdId = queryForm.roomId
    
    const response = await sanitationFeeApi.getSanitationFeeList(params)
    if (response.code === 200) {
      sanitationFeeList.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取卫生费列表失败:', error)
    showMessage({ type: 'error', message: '获取卫生费列表失败' })
  } finally {
    tableLoading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  getSanitationFeeList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    roomId: undefined,
    paymentStatus: undefined,
    billingMonth: ''
  })
  handleSearch()
}

// 生成卫生费
const handleGenerate = () => {
  // 重置生成表单
  Object.assign(generateForm, {
    communityId: undefined as number | undefined, // 修改为undefined类型
    billingMonthRange: [], // 重置月份范围
    dueDate: '' // 重置到期日期
  })
  generateVisible.value = true
}

// 确认生成
const confirmGenerate = async () => {
  // 严格参数验证
  if (!generateForm.communityId || generateForm.communityId === 0 || generateForm.communityId === undefined) {
    showMessage({ type: 'warning', message: '请选择社区' })
    return
  }
  
  if (!generateForm.billingMonthRange || generateForm.billingMonthRange.length !== 2) {
    showMessage({ type: 'warning', message: '请选择计费月份时间段' })
    return
  }

  if (!generateForm.dueDate) {
    showMessage({ type: 'warning', message: '请选择到期日期' })
    return
  }

  try {
    generating.value = true
    
    // 生成一份包含时间段的总费用单
    const requestData = {
      communityId: Number(generateForm.communityId),
      billingMonthRange: generateForm.billingMonthRange,
      dueDate: generateForm.dueDate || '',
      remark: `计费时间段：${generateForm.billingMonthRange[0]} ~ ${generateForm.billingMonthRange[1]}`
    }
    
    console.log('发送卫生费生成请求:', requestData)
    
    const response = await sanitationFeeApi.generateSanitationFee(requestData)
    
    if (response.code === 200) {
      const generatedCount = response.data.count || 0
      showMessage({ type: 'success', message: `成功生成 ${generatedCount} 条卫生费记录` })
      generateVisible.value = false
      getSanitationFeeList()
    } else {
      showMessage({ type: 'error', message: `生成卫生费失败: ${response.message}` })
    }
  } catch (error) {
    console.error('生成卫生费失败:', error)
    showMessage({ type: 'error', message: '生成卫生费失败，请检查参数是否正确' })
  } finally {
    generating.value = false
  }
}

// 生成月份范围
const generateMonthRange = (startMonth: string, endMonth: string): string[] => {
  const months: string[] = []
  const start = new Date(startMonth + '-01')
  const end = new Date(endMonth + '-01')
  
  let current = new Date(start)
  while (current <= end) {
    months.push(current.toISOString().slice(0, 7)) // YYYY-MM格式
    current.setMonth(current.getMonth() + 1)
  }
  
  return months
}


// 缴费
const handlePay = async (row: SanitationFee) => {
  try {
    // 检查支付状态
    if (row.paymentStatus === 1) {
      showMessage({ type: 'warning', message: '该费用已支付，无需重复缴费' })
      return
    }
    
    // 确认缴费
    await ElMessageBox.confirm(
      `确认缴纳卫生费：${row.feeNo}，金额：¥${row.amount}？`,
      '确认缴费',
      {
        confirmButtonText: '确认缴费',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用缴费API
    const billId = Number(row.id)
    if (!billId || isNaN(billId)) {
      showMessage({ type: 'error', message: '无效的账单ID' })
      return
    }
    
    const response = await sanitationFeeApi.paySanitationFee(billId, {
      paymentAmount: row.amount,
      paymentMethod: 'online' // 在线支付
    })
    
    if (response.code === 200) {
      showMessage({ type: 'success', message: '缴费成功' })
      // 刷新列表
      await getSanitationFeeList()
    } else {
      showMessage({ type: 'error', message: response.message || '缴费失败' })
    }
  } catch (error: any) {
    if (error === 'cancel') {
      return
    }
    console.error('缴费失败:', error)
    showMessage({ type: 'error', message: error.message || '缴费失败' })
  }
}

// 催缴
const handleRemind = async (row: SanitationFee) => {
  try {
    await ElMessageBox.confirm('确定要发送催缴提醒吗？', '确认催缴', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 使用现有的API方法，暂时显示开发中提示
    showMessage({ type: 'info', message: '催缴功能开发中...' })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发送催缴提醒失败:', error)
      showMessage({ type: 'error', message: '发送催缴提醒失败' })
    }
  }
}

// 批量催缴
const handleBatchRemind = async () => {
  if (sanitationFeeList.value.length === 0) {
    showMessage({ type: 'warning', message: '暂无数据可催缴' })
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要对 ${sanitationFeeList.value.length} 条未缴费记录发送催缴提醒吗？`, 
      '批量催缴', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用现有的API方法，暂时显示开发中提示
    showMessage({ type: 'info', message: '批量催缴功能开发中...' })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量催缴失败:', error)
      showMessage({ type: 'error', message: '批量催缴失败' })
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    // 暂时显示开发中提示
    showMessage({ type: 'info', message: '导出功能开发中...' })
  } catch (error) {
    console.error('导出失败:', error)
    showMessage({ type: 'error', message: '导出失败' })
  }
}

// 查看详情
const handleViewDetail = (row: SanitationFee) => {
  currentFee.value = row
  detailVisible.value = true
}

// 编辑
const handleEdit = async (row: SanitationFee) => {
  try {
    // 先获取完整的卫生费详情数据
    const response = await sanitationFeeApi.getSanitationFeeDetail(Number(row.id))
    if (response.data) {
      Object.assign(editForm, {
        id: response.data.id,
        feeNo: response.data.feeNo || '',
        householdAddress: response.data.householdAddress || '',
        billingPeriod: response.data.billingPeriod || '',
        amount: response.data.amount || 0,
        dueDate: response.data.dueDate || '',
        paymentStatus: response.data.paymentStatus || 0
      })
    } else {
      // 如果获取详情失败，使用列表数据
      Object.assign(editForm, {
        id: row.id,
        feeNo: row.feeNo || '',
        householdAddress: row.householdAddress || '',
        billingPeriod: row.billingPeriod || '',
        amount: row.amount || 0,
        dueDate: row.dueDate || '',
        paymentStatus: row.paymentStatus || 0
      })
    }
    editVisible.value = true
  } catch (error) {
    console.error('获取卫生费详情失败:', error)
    // 获取详情失败时，使用列表数据
    Object.assign(editForm, {
      id: row.id,
      feeNo: row.feeNo || '',
      householdAddress: row.householdAddress || '',
      billingPeriod: row.billingPeriod || '',
      amount: row.amount || 0,
      dueDate: row.dueDate || '',
      paymentStatus: row.paymentStatus || 0
    })
    editVisible.value = true
  }
}

// 确认编辑
const confirmEdit = async () => {
  try {
    // 表单验证
    await editFormRef.value.validate()
    
    editing.value = true
    
    const requestData = {
      amount: editForm.amount,
      // dueDate: editForm.dueDate, // 注释：到期日期不允许修改
      paymentStatus: editForm.paymentStatus
    }
    
    const response = await sanitationFeeApi.updateSanitationFee(editForm.id, requestData)
    
    if (response.code === 200) {
      showMessage({ type: 'success', message: '编辑成功' })
      editVisible.value = false
      getSanitationFeeList()
    } else {
      showMessage({ type: 'error', message: response.message || '编辑失败' })
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('编辑失败:', error)
      showMessage({ type: 'error', message: '编辑失败，请检查表单数据' })
    }
  } finally {
    editing.value = false
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getSanitationFeeList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  getSanitationFeeList()
}

// 工具函数
const getPaymentStatusTagType = (status: number) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

const getPaymentStatusText = (status: number) => {
  switch (status) {
    case 0: return '未缴费'
    case 1: return '已缴费'
    case 2: return '逾期'
    default: return '未知'
  }
}

const getDueDateClass = (dueDate: string, paymentStatus: number) => {
  if (paymentStatus === 1) return ''
  const due = new Date(dueDate)
  const now = new Date()
  return due < now ? 'text-danger' : ''
}

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

const formatDateTime = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(async () => {
  try {
    // 1. 首先加载用户权限信息
    // await userStore.getUserDataScope() // 移除此行，权限信息已移至 usePermissionUtils
    
    // 2. 然后并行加载业务数据
    await Promise.all([
      getSanitationFeeList(),
      loadCommunityList()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    showMessage({ type: 'error', message: '初始化数据失败' })
  }
})

// 处理ReminderRecordPanel同步成功事件
const handleSyncSuccess = () => {
  detailVisible.value = false; // 关闭详情弹窗
  getSanitationFeeList(); // 刷新卫生费列表
}
</script>

<style scoped>
.sanitation-fee-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.operation-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 16px;
}

.amount-text {
  color: #e6a23c;
  font-weight: bold;
}

.text-danger {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.operation-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.operation-buttons .el-button {
  margin: 0;
  padding: 5px 8px;
  font-size: 12px;
}
</style> 